<?php
// +----------------------------------------------------------------------
// | [KyPHP System] Copyright (c) 2020 http://www.kuryun.com/
// +----------------------------------------------------------------------
// | [KyPHP] 并不是自由软件,你可免费使用,未经许可不能去掉KyPHP相关版权
// +----------------------------------------------------------------------
// | Author: fudaoji <fdj@kuryun.cn>
// +----------------------------------------------------------------------
/**
 * Created by PhpStorm.
 * Script Name: Payment.php
 * Create: 2020/7/21 15:34
 * Description: 平台统一支付
 * Author: fudaoji<fdj@kuryun.cn>
 */

namespace app\system\controller;

use ky\ErWeiCode;
use ky\Payment as PayApi;

class Payment extends Base
{
    /**
     * @var \app\common\model\OrderAddon
     */
    private $orderAddonM;
    public function initialize()
    {
        parent::initialize(); // TODO: Change the autogenerated stub
        $this->orderAddonM = model('orderAddon');
    }

    /**
     * 生成应用开通支付二维码
     * @author fudaoji<fdj@kuryun.cn>
     */
    public function generatePayCode() {
        $code_url = input('code_url', '', 'urldecode');
        $qrClass = new ErWeiCode();
        echo $qrClass->qrCode($code_url);
    }

    /**
     * 发起支付页，所有公众号应用涉及到的网页支付都要跳到此处进行统一支付，因为微信支付的域名配置只有5个
     * @return mixed
     * @throws \think\exception\DbException
     * Author: fudaoji<fdj@kuryun.cn>
     */
    public function orderAddon(){
        $order_no = input('order_no', '');
        $order_info = $this->orderAddonM->getOneByMap(['order_no' => $order_no]);
        if (empty($order_info)){
            $this->error('订单不存在');
        }

        if(request()->isPost()){ //轮询是否已支付
            if($order_info['paid'] == 1){
                $this->success('success');
            }
            $this->error('fail');
        }

        if($order_info['paid'] == 1){
            $this->error('订单已支付');
        }

        $params = [
            'channel'       => $order_info['channel'],
            'mode'          => 2,
            'body'          => $order_info['body'],
            'product_id'    => $order_info['id'],
            'out_trade_no'  => $order_info['order_no'],
            'total_fee'     => (int)$order_info['amount'],
            'notify_url'    => request()->domain() . url('onmessage/payAddonCallBack', ['order_no' => $order_no]),
        ];

        $pay_api = new PayApi(get_pay_config('wx'));
        $result = $pay_api->pay($params);

        if(isset($result['code_url'])) {
            //生成支付二维码
            $order_info['code_url'] = $result['code_url'];
        }else {
            $this->error('发起支付出错，错误原因：' . $result['return_msg']);
        }
        $assign = [
            'order_info'  => $order_info
        ];
        return $this->show($assign);
    }
}